package com.xckj.teacher.ui.fragment

import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.luck.picture.lib.app.PictureAppMaster
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.MediaUtils
import com.xckj.teacher.R
import com.xckj.teacher.bean.BaseBean
import com.xckj.teacher.bean.UploadResponse
import com.xckj.teacher.databinding.DialogTakePhotoBinding
import com.xckj.teacher.framework.BaseDialogFragment
import com.xckj.teacher.framework.net.RetrofitManager
import com.xckj.teacher.global.Constant
import com.xckj.teacher.ui.appViewModel
import com.xckj.teacher.util.GlideEngine
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.Objects


class TakePhotoDialog(var back: () -> Unit) : BaseDialogFragment<DialogTakePhotoBinding>(1) {

    var path = ""
    override fun loadLayout(): Int {
        return R.layout.dialog_take_photo
    }

    override fun initData() {
        dataBinding?.take?.setOnClickListener {
            PictureSelector.create(this.activity)
                .openCamera(SelectMimeType.ofImage())
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(p0: java.util.ArrayList<LocalMedia>) {
                        analyticalSelectResults(p0)
                    }

                    override fun onCancel() {

                    }

                })
        }
        dataBinding?.photo?.setOnClickListener {
            PictureSelector.create(this.activity)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>) {
                        analyticalSelectResults(result)
                    }

                    override fun onCancel() {}
                })
        }
        dataBinding?.cancel?.setOnClickListener {
            dismiss()
        }
    }


    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(this.activity, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(
                        PictureAppMaster.getInstance().appContext,
                        media.path
                    )
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            path = media.realPath
            uploadAvatar(File(media.realPath))
        }

    }


    fun uploadAvatar(file: File) {
        LogUtils.e(file.path)
        showLoading()
        val requestBody = RequestBody.create(
            MediaType.get("multipart/form-data"),
            file
        )
        var createFormData = MultipartBody.Part.createFormData("file", file.name, requestBody)

        val call = RetrofitManager.getInstance().service.uploadFile(createFormData)
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(
                call: Call<ResponseBody>,
                response: Response<ResponseBody>
            ) {
                hideLoading()
                if (response.code() == 200) {
                    try {
                        var fromJson = Gson().fromJson(
                            response.body()?.string(),
                            UploadResponse::class.java
                        )
                        LogUtils.e("fromJson:$fromJson")
                        if (fromJson.code == 1) {
                            update(fromJson.data.fullurl)
                        } else {
                            ToastUtils.showShort(fromJson.msg + "")
                        }
                    } catch (e: Exception) {
                        LogUtils.e("error:${e.message}")
                    }

                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                t.printStackTrace()
                hideLoading()
                ToastUtils.showShort("请求失败")
            }
        })
    }

    private fun update(avatar: String) {
        showLoading()
        val call = RetrofitManager.getInstance().service.updateProfile(avatar)
        call.enqueue(object : Callback<BaseBean<Any?>> {
            override fun onResponse(
                call: Call<BaseBean<Any?>>,
                response: Response<BaseBean<Any?>>
            ) {
                hideLoading()
                if (response.isSuccessful) {
                    val baseBean = response.body()!!
                    if (Constant.SUCCESS_CODE == Objects.requireNonNull(baseBean).code) {
                        ToastUtils.showShort("头像上传成功")
                        appViewModel.lccal.value = path
                        dismiss()
                    } else {
                        ToastUtils.showShort(baseBean.msg)
                    }
                } else {
                    ToastUtils.showShort("请求失败")
                }
            }

            override fun onFailure(call: Call<BaseBean<Any?>>, t: Throwable) {
                t.printStackTrace()
                hideLoading()
                ToastUtils.showShort("请求失败")
            }
        })
    }


}